package com.zhss.demo.concurrent;

/**
 * @author xuhua
 * @create 2021-11-29 21:11
 * @description 线程不安全案例
 */
public class ThreadUnsafeDemo {

    private static int DATA_SIZE = 0;

    public static void main(String[] args) throws InterruptedException {

        ThreadUnsafeDemo demo = new ThreadUnsafeDemo();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                //increment();
                // 对实例对象加锁
                //demo.increment1();
                // demo.increment2();
                synchronized (ThreadUnsafeDemo.class) {
                    ThreadUnsafeDemo.DATA_SIZE++;
                    System.out.println(DATA_SIZE);
                }
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                //increment();
                //demo.increment1();
                //demo.increment2();
                synchronized (ThreadUnsafeDemo.class) {
                    ThreadUnsafeDemo.DATA_SIZE++;
                    System.out.println(DATA_SIZE);
                }
            }
        });
        thread2.start();
    }

    private synchronized static void increment() {
        ThreadUnsafeDemo.DATA_SIZE++;
        System.out.println(DATA_SIZE);
    }

    private synchronized void increment1() {
        ThreadUnsafeDemo.DATA_SIZE++;
        System.out.println(DATA_SIZE);
    }

    private void increment2() {
        synchronized (this) {
            ThreadUnsafeDemo.DATA_SIZE++;
            System.out.println(DATA_SIZE);
        }
    }
}
